/**
 * Copyright (c) 2014-2015, Suredy technology Co., Ltd. All rights reserved.
 * @author ZhangMaoren 
 * @since 2015年6月15日
 * @version 0.1
 */
package com.suredy.base.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;

import com.suredy.base.model.Permission;
import com.suredy.base.model.Resource;
import com.suredy.core.service.BaseSrvWithEntity;



/**
 * @author ZhangMaoren
 *
 */
@Service("PermissionSrv")
public class PermissionSrv extends BaseSrvWithEntity<Permission> {
	@Override
	public DetachedCriteria getDc(Permission t) {
		DetachedCriteria dc = super.getDc(t);

		if (t == null) {
			return dc;
		}
		
		if (!StringUtils.isBlank(t.getId())) {
			dc.add(Restrictions.eq("id", t.getId()));
		}
		
		if (t.getResource() != null) {
			dc.add(Restrictions.eq("resource", t.getResource()));
		}
		
		if (!StringUtils.isBlank(t.getResourceUri())) {
			dc.add(Restrictions.eq("resourceUri", t.getResourceUri()));
		}
		
		if (t.getAction() != null) {
			dc.add(Restrictions.eq("action", t.getAction()));
		}

		return dc;
	}
	
	public List<Permission> getAll() {
		return this.readByEntity(null);
	}

	public Permission get(String id) {
		return this.get(id);
	}
	
	
	public Permission GetOrCreate(String resourceId, String resourceUrl, Integer action ) {
		Permission search = new Permission();
		search.setAction(action);
		Resource resource = new Resource();
		resource.setId(resourceId);
		search.setResource(resource);
		search.setResourceUri(resourceUrl);
		Permission ret = this.readSingleByEntity(search);
		if (ret == null) {
			this.save(search);
			ret = search;
		} 
		return ret;
	}
	
	public List<Permission> getById(String resourceId) {
		List<Permission> ret = new ArrayList<Permission>(); 
		if (StringUtils.isBlank(resourceId)) {
			return ret;
		}
		Permission search = new Permission();
		Resource resource = new Resource();
		resource.setId(resourceId);
		search.setResource(resource);
		ret = this.readByEntity(search);
		return ret;
	}
	
	public List<Permission> getByUrl(String resourceUri) {
		List<Permission> ret = new ArrayList<Permission>(); 
		if (StringUtils.isBlank(resourceUri)) {
			return ret;
		}
		Permission search = new Permission();
		search.setResourceUri(resourceUri);
		ret =  this.readByEntity(search);
		return ret;
	}

	
}
